package com.module.prms;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import base.util.MD5Util;
import base.util.Page;

import com.module.organization.OrganizationService;
import com.module.organization.vo.Organization;
import com.module.prms.manager.UserManager;
import com.module.prms.vo.PrmsRoleOrg;
import com.module.prms.vo.PrmsUser;
import com.module.prms.vo.PrmsUserOrg;
import com.module.sys.LoginSession;
import com.webClient.client.SocketClient;
import com.webClient.service.WebClientService;



public class prmsUserService {
	static Logger logger = Logger.getLogger(prmsUserService.class.getName ()) ;
	static SocketClient sClient = null;
	static WebClientService ss = null;
	public OrganizationService orgs =null;



	
	
	/**
	 * 用户列表
	 * @param pu
	 * @param start
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	public Page list(PrmsUser pu, final Integer start, final Integer limit)
			throws Exception {
		Page page = new Page();
		page.setStart(start);
		page.setLimit(limit);
		pu.setChildListId(LoginSession.getOrgids());
		UserManager userManager = UserManager.getInstance();
		Page resultPage = userManager.list(page, pu);
		return resultPage;

	}

	public List orgtree() {
		try {
			return orgs.getSelfTree(LoginSession.getOrgid());
		} catch (Exception e) {
			logger.error("权限-->用户管理-->获取组织树失败：" + e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	 
	public List orgList() {
		try {
			return orgs.getJustList();
		} catch (Exception e) {
			logger.error("权限-->用户管理-->获取组织失败：" + e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	 
	public PrmsUser findbyid(String userid) {
		try {
			PrmsUser pu = new PrmsUser();
			pu.setCuserId(userid);
			UserManager userManager = UserManager.getInstance();
			PrmsUser prmsUser = userManager.findebyid(pu);
			return prmsUser;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	 /**
	  * 根据用户名查询
	  * @param username
	  * @return
	  */
	 public PrmsUser findUserbyName(String username){
	  try {
	 	    PrmsUser pu =new PrmsUser();
	 	    pu.setCuserName(username);
	 	    UserManager userManager = UserManager.getInstance();
	 	    PrmsUser prmsUser =userManager.findUserbyName(pu);
			return prmsUser;
		} catch (Exception e) {
			
			e.printStackTrace();
			return null;
		}
	 }
	 /**
	  * 新增用户
	  * @param pu
	  * @param orgs
	  * @param isEdit
	  * @return
	 * @throws UnsupportedEncodingException 
	 * @throws NoSuchAlgorithmException 
	  */
	public Map save(PrmsUser pu, List orgs, int isEdit) throws Exception {
		UserManager userManager = UserManager.getInstance();
		if (isEdit == 0) {
			// 修改密码时重新加密
			pu.setCuserPwd(MD5Util.EncoderByMd5(pu.getCuserPwd()));
		}
		List uorglist = new ArrayList();
		System.out.println(orgs.size());
		for (int i = 0; i < orgs.size(); i++) {
			//Map tmap = (Map) orgs.get(i);
			Organization organization=(Organization)orgs.get(i);
			PrmsUserOrg puo = new PrmsUserOrg();
			puo.setCorgId(organization.getId());
			uorglist.add(puo);
		}
		pu.setOrgs(uorglist);
		boolean isTrue = userManager.add(pu);
		Map<String, Object> statusMap = new HashMap<String, Object>();
		statusMap.put("state", isTrue);
		if (isTrue == true) {
			statusMap.put("msg", "保存成功");
		} else {
			statusMap.put("msg", "保存失败");
		}
		return statusMap;
	}

	 /**
	  * 删除用户
	  * @param idArray
	  * @return
	  * @throws Exception
	  */
	 public Map remove(List<String> idArray) throws Exception{
 	    UserManager userManager = UserManager.getInstance();
 	    boolean flag=userManager.remove(idArray);
 	    Map<String, Object> statusMap = new HashMap<String, Object>();
		statusMap.put("state", flag);
		if(flag==true){
			statusMap.put("msg", "删除成功");
		}else{
			statusMap.put("msg", "删除失败");
		}
 	    return statusMap;
	 }
	 
	
	 
	 public OrganizationService getOrgs() {
			return orgs;
		}


		public void setOrgs(OrganizationService orgs) {
			this.orgs = orgs;
		}
		
		
		/**
		 * 获取组织下的角色
		 * parm:orgid
		 */
		public List getorg_role(String orgid)
		{
			PrmsRoleOrg pro = new PrmsRoleOrg();
			pro.setCorgId(orgid);
			UserManager userManager = UserManager.getInstance();//getorg_role
			List list = new ArrayList();
			try {
				list = userManager.getorg_role(pro);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		}

		/**
		 * 保存与用户并联的角色
		 * parm:orgid
		 */
		public Map saveUserRole(String userid,List Roleidlist)
		{
			Map<String, Object> statusMap = new HashMap<String, Object>();
			UserManager userManager = UserManager.getInstance();
			try {
				boolean flag =userManager.saveUserRole(userid,Roleidlist);
				
				statusMap.put("state", flag);
				if(flag==true){
					statusMap.put("msg", "保存成功");
				}else{
					statusMap.put("msg", "保存失败");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 return statusMap;
		}
		

		public List getUserRole(String userid)
		{
			List list = new ArrayList();
			UserManager userManager = UserManager.getInstance();
			try {
				 list=userManager.getUserRole(userid);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list;
		}
		
		
		/**
		 * 登陆时获得用户信息
		 * parm:orgid
		 */
		public PrmsUser getUserInfo(String username,String password)
		{
			UserManager userManager = UserManager.getInstance();
			PrmsUser pu = new PrmsUser();
			pu.setCuserName(username);
			try {
				pu.setCuserPwd(MD5Util.EncoderByMd5(password));
				PrmsUser prmsUser=userManager.getUserInfo(pu);
				 return  prmsUser;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} 
		}
		
		
		/**
		 * 是否有预警权限
		 * @return
		 */
		public Boolean hasWarnInfoRight() {
			boolean result = false;
			/*
			List menuTree =  LoginSession.getMenutree();
			System.out.println("tree:::::\t"+menuTree); 
			if(menuTree!=null){
			    for(Object obj : menuTree){
			    	ASObject asObj = (ASObject) obj;
			    	if("防伪管理".equals(asObj.get("cmenuName"))){
			    		List children = (List) asObj.get("children");
			    		for(Object childObj : children){
			    			ASObject fanObj = (ASObject) childObj;
			    			if("预警管理".equals(fanObj.get("cmenuName"))){
			    				result = true;
			    			}
			    		}
			    		break;
			    	}
			    }
			}
			*/
			return result;
		}


		/**
		 * 获取用户菜单信息
		 * parm:roleid
		 */
		public List getUserMenu(String roleid)
		{
			UserManager userManager = UserManager.getInstance();
			try {
				List UMenu=(List)userManager.getUserMenu(roleid).get("menulist");
				return UMenu;
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return null;
			}
		}		
		
		
	public static void main(String args[])
	{
		prmsUserService ps = new prmsUserService();
		try {
			//ps.list(0, 5);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean isEqualPwd(String oldPwd){
		if(LoginSession.getPwd().equals(oldPwd))
			return true;
		
		return false;
	}
	
	//修改密码
	public boolean saveUser(PrmsUser userInfo){
	  	try {
			boolean flag= false;
			String pwd  = userInfo.getCuserPwd();
			userInfo.setCuserPwd(MD5Util.EncoderByMd5(pwd));
			UserManager userManager = UserManager.getInstance();
			flag=userManager.changePassword(userInfo);
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	public boolean changePassword(String userName,String pwd){
		PrmsUser userInfo = findUserbyName(userName);
		userInfo.setCuserPwd(pwd);
		return saveUser(userInfo);
	}
	public boolean changePassword(String newPwd){
		PrmsUser userInfo = getUserInfo(LoginSession.getUsername(), LoginSession.getPwd());
		userInfo.setCuserPwd(newPwd);
		return saveUser(userInfo);
	  	 
	}

}
